package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.publish;

import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.mcas.di.scope.ActivityScope;
import com.kaiwukj.android.mcas.mvp.BasePresenter;
import com.kaiwukj.android.mcas.utils.RxLifecycleUtils;
import com.kaiwukj.android.ufamily.exception.UploadException;
import com.kaiwukj.android.ufamily.mvp.http.callback.ApiCallBack;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.DynamicPubParams;
import com.kaiwukj.android.ufamily.mvp.http.utils.RxUtils;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.utils.upload.OnUploadListener;
import com.kaiwukj.android.ufamily.utils.upload.UploadBean;
import com.kaiwukj.android.ufamily.utils.upload.UploadUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.inject.Inject;

import io.reactivex.Observable;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

@ActivityScope
public class DynamicPublishPresenter extends BasePresenter<DynamicContract.Model, DynamicContract.PublishView> {

    public static final int PUBLISH = 1;

    @Inject
    RxErrorHandler mErrorHandler;

    @Inject
    public DynamicPublishPresenter(DynamicContract.Model model, DynamicContract.PublishView view) {
        super(model, view);
    }

    public void publishDynamic(DynamicPubParams params) {
        mModel.publishDynamic(params)
                .doOnSubscribe(act -> mRootView.showLoading("正在发布..."))
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<Integer>(mErrorHandler, mRootView, PUBLISH) {
                    @Override
                    public void onSuccess(@NonNull Integer result) {
                        LogUtils.d("发布成功");
                        mRootView.showMessage("发布成功");
                    }
                });
    }

    public void publish() {
    }

    /**
     * 获取七牛云Token
     * isVideo 是否发布视频 false为只发布图片
     */
    public void requestQIToken(DynamicPubParams params, List<String> paths, boolean isVideo) {
        mModel.getQiNiuToken()
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading("正在处理...");
                })
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<String>(mErrorHandler) {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(@NonNull String result) {
                        //上传图片的缩略图或者帖子的图片
                        if (isVideo) {
                            Observable<String> imgObservable = Observable.create(emitter ->
                            {
                                UploadUtils uploadUtils = new UploadUtils();
                                uploadUtils.upload(params.getImages(), result, UploadUtils.IMAGE,
                                        new OnUploadListener() {
                                            @Override
                                            public void onUploadImage(UploadBean result) {
                                                //request.setVideo(result.getNormalUrl());
                                                //postSocialCard(request);
                                                emitter.onNext(result.getNormalUrl());
                                            }

                                            @Override
                                            public void onUploadImages(List<UploadBean> results) {

                                            }

                                            @Override
                                            public void onError(int errCode, String errMsg) {
                                                //mRootView.showMessage(errMsg);
                                                emitter.onNext("上传失败:" + errCode + ":" + errMsg);
                                            }
                                        });

                            });

                            Observable<String> videoObservable = Observable.create(
                                    emitter -> {
                                        UploadUtils uploadUtils = new UploadUtils();
                                        uploadUtils.upload(paths.get(0), result, UploadUtils.VIDEO, new OnUploadListener() {
                                            @Override
                                            public void onUploadImage(UploadBean result) {
                                                emitter.onNext(result.getNormalUrl());
                                            }

                                            @Override
                                            public void onUploadImages(List<UploadBean> results) {

                                            }

                                            @Override
                                            public void onError(int errCode, String errMsg) {
                                                emitter.onError(new UploadException(errCode, errMsg));
                                            }
                                        });
                                    });

                            addDispose(Observable.zip(imgObservable, videoObservable, (s, s2) -> {
                                Map<String, String> map = new HashMap<>();
                                map.put("image", s);//预览图
                                map.put("video", s2);
                                return map;
                            }).subscribe(stringObjectMap -> {
                                LogUtils.d("json------------------------->" + GsonUtils.toJson(stringObjectMap));
                                params.setImages(stringObjectMap.get("image"));
                                params.setVideo(stringObjectMap.get("video"));
                                publishDynamic(params);
                            }, e -> {
                                LogUtils.e("e---------------->" + e.getMessage());
                            }));
                        } else {

                            UploadUtils.getInstance().uploadImages(paths, result, new OnUploadListener() {
                                @Override
                                public void onUploadImage(UploadBean result) {

                                }

                                @Override
                                public void onUploadImages(List<UploadBean> results) {
                                    //  LogUtils.d("path-------------------->" + GsonUtils.toJson(results));
                                    List<String> urls = new ArrayList<>();
                                    for (UploadBean result : results) {
                                        urls.add(result.getNormalUrl());
                                    }
                                    params.setImages(urls.stream().collect(Collectors.joining(",")));
                                    publishDynamic(params);
                                }

                                @Override
                                public void onError(int errCode, String errMsg) {
                                    LogUtils.d("onError------------->" + errCode + ":" + errMsg);
                                }
                            });
                        }

                    }
                });
    }

}
